# !/usr/bin/python3
# coding:utf-8
import os
import re
import json
import time
import datetime

data_format = [
    ('stock_id', str),
    ('stock_name', str),
    ('today_open', float),
    ('yesterday_close', float),
    ('current_price', float),
    ('today_high', float),
    ('today_low', float),
    ('cur_buy_price', float),   # 竞买价
    ('cur_sell_price', float),  # 竞卖价
    ('deal_quantity', float),   # 成交量
    ('deal_amount', float),     # 成交金额
    ('buy1_quantity', float),
    ('buy1_price', float),
    ('buy2_quantity', float),
    ('buy2_price', float),
    ('buy3_quantity', float),
    ('buy3_price', float),
    ('buy4_quantity', float),
    ('buy4_price', float),
    ('buy5_quantity', float),
    ('buy5_price', float),
    ('sell1_quantity', float),
    ('sell1_price', float),
    ('sell2_quantity', float),
    ('sell2_price', float),
    ('sell3_quantity', float),
    ('sell3_price', float),
    ('sell4_quantity', float),
    ('sell4_price', float),
    ('sell5_quantity', float),
    ('sell5_price', float),
    ('date', str),
    ('time', str),
    ('millisecond', int)
]


class DataHandler(object):

    def __init__(self):
        self.data_dic = {}
        data_dir = '../client'
        for file_name in os.listdir(data_dir):
            if file_name.endswith('cleared.csv'):
                share_id = re.match('share_data_(.*)_cleared.csv', file_name).groups()[0]
                self.data_dic[share_id] = infos = []
                with open(os.path.join(data_dir, file_name), encoding="utf-8") as fp:
                    for line in fp.readlines():
                        raw_info = line.rstrip('\n').split(',')
                        info = {}
                        for i, (name, method) in enumerate(data_format):
                            info[name] = method(raw_info[i])
                        info['year'], info['month'], info['day'] = map(int, info['date'].split('-'))
                        info['hour'], info['minute'], info['second'] = map(int, info['time'].split(':'))
                        date_time = datetime.datetime(info['year'], info['month'], info['day'], info['hour'], info['minute'], info['second'])
                        info['timestamp'] = date_time.timestamp()
                        infos.append(info)

        self.fake_start_timestamp = datetime.datetime(2019, 5, 6, 9, 30, 0).timestamp()
        self.time_offset = 0

    def set_start_now(self):
        """设定当前时间为开盘时间"""
        self.time_offset = self.fake_start_timestamp - time.time()

    def get_time(self):
        return time.time() + self.time_offset

    def get_info(self, timestamp, stock_id='sz300059'):
        timestamp += self.time_offset
        print('cur', datetime.datetime.fromtimestamp(timestamp))
        for info in self.data_dic[stock_id]:
            # print(datetime.datetime.fromtimestamp(info['timestamp']))
            if info['timestamp'] >= timestamp:
                return json.dumps(info)

        return self.data_dic[stock_id][-1]


if __name__ == '__main__':
    handler = DataHandler()
    handler.set_start_now()
    print(handler.get_info(time.time()))
    time.sleep(5)
    print(datetime.datetime.fromtimestamp(handler.get_time()))
    print(handler.get_info(time.time()))
    time.sleep(30)
    print(handler.get_info(time.time()))
